package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.product.pojo.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.vo.ProductSkuVo;
import com.spzx.product.vo.SkuPriceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-03-12
 */
@Service
@Slf4j
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {

    @Override
    public List<ProductSkuVo> getTopSale() {
        return baseMapper.getTopSale();
    }

    @Override
    public List<ProductSkuVo> selectProductSkuList(SkuQuery skuQuery) {
        return baseMapper.selectProductSkuList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {
        // 根据skuId查询商品价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(ProductSku::getId, skuId)
                .select(ProductSku::getSalePrice, ProductSku::getMarketPrice);
        ProductSku productSku = baseMapper.selectOne(queryWrapper);

        // 封装数据
        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setSkuId(skuId);
        return skuPriceVo;
    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        // 查询一个商品的所有sku
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(ProductSku::getProductId, id)
                // 需要什么数据就组装什么数据，提高效率，减少服务器压力
                .select(ProductSku::getId, ProductSku::getSkuSpec);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);

        // 封装数据
        Map<String,Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }

    // 优化
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public ProductSku getProductSkuById(Long skuId) {
        // 从 redis中获取 sku信息
        String dataKey = "product:sku" + skuId;
        ProductSku productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);

        // 若有直接返回
        if (productSku != null) {
            return productSku;
        }

        // 加分布式锁
        log.info("加分布式锁");
        String lockKey = "product:stu:lock" + skuId;
        String lockValue = UUID.randomUUID().toString().replaceAll("-", "");
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 30, TimeUnit.SECONDS);
        if (flag) {
            log.info("获取到分布式锁");
            try {
                // 再次从 redis中获取信息，若有则直接返回
                productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
                if (productSku != null) {
                    return productSku;
                }

                // 若没有则查询数据库
                log.info("进入数据库查询");
                productSku = baseMapper.selectById(skuId);
                // 设置空值，但是无法阻止随机穿透
                long ttl = 60;
                if (productSku == null) {
                    productSku = new ProductSku();
                    ttl = 30;
                }

                // 将查询到的数据保存到 redis中
                redisTemplate.opsForValue().set(dataKey, productSku, ttl, TimeUnit.SECONDS);

                return productSku;
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                // 释放锁
                String script = """
                       if redis.call('get', KEYS[1]) == ARGV[1] then
                           return redis.call('del', KEYS[1])
                       else
                           return 0
                       end
                       """;
                Boolean lock = (Boolean) redisTemplate.execute(
                        new DefaultRedisScript<Boolean>(script, Boolean.class),
                        Arrays.asList("lockKey"),
                        lockValue);
                System.out.println("锁释放成功：" + lock);
            }
        } else {
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            return getProductSkuById(skuId);
        }
    }

    /**
     * 查询商品列表的最新价格
     * @param skuIdList
     * @return
     */
    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        List<ProductSku> productSkuList = baseMapper.selectList(new LambdaQueryWrapper<ProductSku>()
                .in(ProductSku::getId, skuIdList)
                .select(ProductSku::getId, ProductSku::getSalePrice)
        );

        if (!CollectionUtils.isEmpty(productSkuList)) {
            List<SkuPriceVo> skuPriceVoList = productSkuList
                    .stream()
                    .map(productSku -> {
                        SkuPriceVo skuPriceVo = new SkuPriceVo();
                        skuPriceVo.setSkuId(productSku.getId());
                        skuPriceVo.setSalePrice(productSku.getSalePrice());
                        return skuPriceVo;
                    })
                    .toList();

            return skuPriceVoList;
        }

        return null;
    }
}
